package com.carpedil.shirodemo.system.mapper;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.carpedil.shirodemo.system.model.User;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Set;

/**
 * 用户表 Mapper 接口
 *
 * @author carpedil
 * @since 2021-01-05
 */
@Repository
public interface UserMapper extends BaseMapper<User> {
  /**
   * 查询所有用户并分页
   *
   * @param page mybatis-plus的page对象
   * @param wrapper mybatis-plus条件查询对象
   * @return 分页的page对象
   */
  IPage<User> selectAllWithDept(Page<User> page, @Param(Constants.WRAPPER) Wrapper<User> wrapper);

  /**
   * 根据用户名获取拥有的所有角色名
   *
   * @param username 登录用户名
   * @return 该用户拥有的所有角色名
   */
  @Select(
      "select r.role_name "
          + " from user_role ur "
          + " INNER JOIN user u on u.user_id = ur.user_id "
          + " INNER JOIN role r on r.role_id = ur.role_id "
          + " WHERE u.username = #{username}")
  @ResultMap("com.carpedil.shirodemo.system.mapper.UserMapper.userMap")
  Set<String> selectRoleNameByUserName(@Param("username") String username);

  /**
   * 获取用户所拥有的操作权限
   *
   * @param username 登录用户名
   * @return 该用户拥有操作权限的Set集合
   */
  @Select(
      "select o.perms "
          + " from user_role ur "
          + " INNER JOIN user u on u.user_id = ur.user_id "
          + " INNER JOIN role r on r.role_id = ur.role_id "
          + " INNER JOIN role_operator ro on ro.role_id = r.role_id "
          + " INNER JOIN operator o on o.operator_id = ro.operator_id "
          + " WHERE u.username = #{username}")
  Set<String> selectOperatorPermsByUserName(@Param("username") String username);

  @Update("update user set status = 1 where user_id = #{userId}")
  int enable(@Param("userId") Integer userId);

  @Update("update user set status = 0 where user_id = #{userId}")
  int disable(@Param("userId") Integer userId);

  @Select("select username from user where dept_id = #{id}")
  @ResultMap("com.carpedil.shirodemo.system.mapper.UserMapper.userMap")
  List<User> selectUserByDeptId(@Param("id") Integer id);
}
